﻿using UnityEngine;
using System.Collections;

[RequireComponent(typeof(BoxCollider))]
public class PlayerPhysics : MonoBehaviour {
		
	public LayerMask collisionMask; 
	
	private BoxCollider collider;
	private Vector3 colliderSize; 
	private Vector3 colliderCenter;
		
	private float objBuf = .005f; // Buffer between player and wall for raycast
	private bool wallHit; 
	
	Ray colliderRay;
	RaycastHit hit;

	public GameObject Projectile;
	
	//private ArrayList projectiles = new ArrayList();
	
	int projSpeed = 10000;

	void Start() {
		collider = GetComponent<BoxCollider>();
		colliderSize = collider.size;
		colliderCenter = collider.center;
	}
	public void Move(Vector2 movement){
		
		// Checking for collision with wall gameObjects
		float dX = movement.x; 
		Vector2 pos = transform.position; 
		
		float direction = Mathf.Sign(dX); 
		float x = pos.x + colliderCenter.x + colliderSize.x/2 * direction; 
		float y = (pos.y + colliderCenter.y - colliderSize.y/2); 
		
		colliderRay = new Ray(new Vector2(x,y), new Vector2(direction, 0));
		Debug.DrawRay(colliderRay.origin, colliderRay.direction);

		if(Physics.Raycast(colliderRay, out hit, Mathf.Abs(dX) + objBuf, collisionMask)){
			float dist = Vector3.Distance(colliderRay.origin, hit.point);
			if(dist > objBuf){
				dX = dist * direction - objBuf * direction;
			}
			else dX = 0; 
		}
		
		Vector2 finalMove = new Vector2(dX, 0);
		transform.Translate(finalMove);
	}
	
	public void Update(){
	}

	/* public void Fire(Vector2 vecToMousePos, Point mousePos)
	 *  Get the vector to the target mouse pos (the ray vector from PlayerController...?)
	 *  Normalize vector
	 *  Spawn gameObject bullet / whatever
	 *  Set bullet velocity to speed * normalTargetPos
	 *   
	 *  Either have bullet collide with sheep or stop at mousePos
	 */
	public void Fire(Vector2 toTarget, Vector3 mousePoint, Vector3 playerPos, Quaternion playerRot) {
		if(GameManager.numProjectiles >= GameManager.maxProjectiles)
			return;
		
		GameObject newProjectile = (GameObject)Instantiate(Projectile, playerPos, playerRot) as GameObject;
		newProjectile.AddComponent("ProjectileBehavior");
		ProjectileBehavior proj = (ProjectileBehavior)((GameObject)newProjectile).GetComponent("ProjectileBehavior");
		proj.setTarget(mousePoint);
		Vector3 forceVector = (mousePoint-playerPos);
		forceVector.Normalize();
		forceVector *= projSpeed;
		//proj.setForceVector(forceVector);
		
		((GameObject)newProjectile).rigidbody.AddForce(forceVector);//((projSpeed * mousePoint));
		// Use Physics.raycast from instantiated projectile to detect collision
	}
}
